var express = require('express');
var router = express.Router();
const { User } = require('../models');
const Post = require('../models/post');
const jwt = require('jsonwebtoken');

const authenticateUser = async (req, res, next) => {
    const token = req.header('Authorization').replace('Bearer ', '');
    console.log(token)
    console.log(233)
    const decoded = jwt.verify(token, "11111112324");
    const user = await User.findById(decoded.id);

    if (!user) {
      throw new Error();
    }

    req.user = user;
    req.token = token;
    next();
};


router.get('/create-user', async (req, res) => {
  try {
    // 注意：GET 请求通常从查询参数获取数据，而不是请求体
    const { username, email, password } = req.query;
    
    if (!username || !email || !password) {
      return res.status(400).json({ error: 'Missing required parameters: username, email, password' });
    }

    const user = new User({
      username,
      email,
      password
    });
    
    await user.save();
    res.status(201).json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});


router.post('/register', async (req, res) => {
  try {
      const { username, email, password } = req.body;

      // 检查必填参数
      if (!username || !email || !password) {
          return res.status(400).json({ error: 'Missing required parameters: username, email, password' });
      }

      // 检查用户名和邮箱是否已存在
      const { exists, errors } = await User.checkExists(username, email);
      if (exists) {
          return res.status(400).json({ errors });
      }

      // 创建新用户
      const user = new User({
          username,
          email,
          password
      });

      // 保存用户到数据库
      await user.save();

      // 生成 JWT 令牌
      const token = user.generateAuthToken();

      // 返回用户信息和令牌
      res.status(201).json({ user: user.getProfile(), token });
  } catch (err) {
      res.status(400).json({ error: err.message });
  }
});

router.post('/login', async (req, res) => {
  try {
    const { identifier, password } = req.body;
    const user = await User.findByCredentials(identifier, password);
    const token = user.generateAuthToken();
    res.status(200).json({ user: user.getProfile(), token });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});


router.get('/protected-posts', authenticateUser, async (req, res) => {
  try {
    const posts = await Post.find()
      .populate('author', 'username')
      .populate('categories', 'name')
      .populate('tags', 'name');
    res.status(200).json(posts);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});



// 新增路由，通过 ID 获取文章详细内容
router.get('/posts/:id', async (req, res) => {
  try {
      const postId = req.params.id;
      const post = await Post.findById(postId)
         .populate('author', 'username')
         .populate('categories', 'name')
         .populate('tags', 'name');

      if (!post) {
          return res.status(404).json({ error: '文章未找到' });
      }

      res.status(200).json(post);
  } catch (err) {
      res.status(500).json({ error: err.message });
  }
});


router.get('/posts', async (req, res) => {
  try {
    const posts = await Post.find()
      .populate('author', 'username') // 关联查询作者信息，只返回 username 字段
      .populate('categories', 'name') // 关联查询分类信息，只返回 name 字段
      .populate('tags', 'name'); // 关联查询标签信息，只返回 name 字段
    res.status(200).json(posts);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
